package com.hexus.eve.actions.security;

import java.util.List;
import java.util.ResourceBundle;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.security.authentication.dao.SaltSource;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;

import com.hexus.eve.entities.security.SecurityGroup;
import com.opensymphony.xwork2.ActionSupport;
import com.hexus.eve.entities.security.User;

public class UpdateUser extends ActionSupport {
	private static final long serialVersionUID = 1L;
	
	@Autowired
	private SessionFactory sessionFactory;
	@Autowired
	private ShaPasswordEncoder shaEncoder;
	@Autowired
	private SaltSource saltSource;
	
	private List<Integer> groups;
	private Boolean isNew = false;
	User user = new User();
	
	@Override
	public String execute() throws Exception {
		HibernateTemplate ht = new HibernateTemplate(sessionFactory);

		
		//Update or creation of a new item
		User existedUser = ht.get(User.class, user.getName()); 
		if(existedUser != null) {
			existedUser.setEnabled(user.isEnabled());
			existedUser.setEmail(user.getEmail());
			
			if(!"".equals(user.getPassword()))
				existedUser.setPassword(user.getPassword());
			
			user = existedUser;
		} else {
			isNew = true;
		}
		
		//Encoding password
		user.setPassword(shaEncoder.encodePassword(user.getPassword(), saltSource.getSalt(user)));
		
		//Updating groups
		user.getGroups().clear();
		for(Integer id : groups) {
			SecurityGroup g = ht.get(SecurityGroup.class, id);
			if(g != null)
				user.getGroups().add(g);
		}

		if(isNew) {
			ht.save(user);			
		} else {
			ht.update(user);			
		}
		
		return SUCCESS;
	}

	
	@Override
	public void validate() {
		HibernateTemplate ht = new HibernateTemplate(sessionFactory);
		User existedUser = ht.get(User.class, user.getName());
		if(existedUser == null && "".equals(user.getPassword())) {
			ResourceBundle bundle = ResourceBundle.getBundle ("global", getLocale());
			addFieldError("user.password", bundle.getString("validation.not.empty"));
		}
		
		if(groups.size() == 0) {
			ResourceBundle bundle = ResourceBundle.getBundle ("global", getLocale());
			addFieldError("groups", bundle.getString("validation.not.empty"));
		}
	}		
	
	
	
	public List<SecurityGroup> getGroups(){
		HibernateTemplate ht = new HibernateTemplate(sessionFactory);
		return ht.loadAll(SecurityGroup.class);
	}

	public void setGroups(List<Integer> groups) {
		this.groups = groups;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
	
	public List<Integer> getSelectedGroups(){
		return groups;
	}	
}
